package handlers

import (
	"bloggo/bloggo"
	"bloggo/dto"
	"bloggo/service"
	"bloggo/structs"
	"context"
	"fmt"
	"gitee.com/chunanyong/zorm"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

// Categories 分类列表
func Categories(c *gin.Context) *bloggo.R {
	page := zorm.NewPage()
	keywords := c.DefaultQuery("keywords", "")
	page.PageNo, _ = strconv.Atoi(c.DefaultQuery("current", "1"))
	page.PageSize, _ = strconv.Atoi(c.DefaultQuery("size", "10"))
	finder := zorm.NewFinder()
	finder.Append(`SELECT
							id,
							category_name AS categoryName,
							(
							SELECT
								COUNT(1)
							FROM
								tb_article
							WHERE
								category_id = tb_category.id ) AS articlecount,
							create_time
						FROM
							tb_category WHERE 1=1`)
	var categoriesDTO []dto.CategorieDTO
	finder.CountFinder = zorm.NewFinder().Append(" select count(*) from tb_category WHERE 1=1")
	if len(keywords) > 0 {
		finder.Append("AND category_name LIKE ?", fmt.Sprint("%", keywords, "%"))
		finder.CountFinder.Append("AND category_name LIKE ?", fmt.Sprint("%", keywords, "%"))
	}
	err := zorm.Query(c, finder, &categoriesDTO, page)
	if err != nil {
		return bloggo.FailMessage(err.Error())
	}
	return bloggo.OkData(gin.H{
		"recordList": categoriesDTO,
		"count":      page.TotalCount,
	})
}

// CategorieSearch 分类列表搜索
func CategorieSearch(c *gin.Context) *bloggo.R {
	keywords := c.DefaultQuery("keywords", "")
	finder := zorm.NewFinder()
	finder.Append("SELECT id,category_name AS categoryName FROM").Append(structs.TbCategoryStructTableName)
	finder.Append("WHERE category_name LiKE ?", fmt.Sprint("%", keywords, "%"))
	finder.Append("ORDER BY id ASC")
	var categoriesDTO []dto.CategorieDTO
	err := zorm.Query(c, finder, &categoriesDTO, nil)
	if err != nil {
		return bloggo.FailMessage(err.Error())
	}
	return bloggo.OkData(categoriesDTO)
}

// SaveOrUpdateCategories 更新分类列表
func SaveOrUpdateCategories(c *gin.Context) *bloggo.R {
	var categoriesDTO dto.CategorieDTO

	err := c.ShouldBind(&categoriesDTO)
	if err != nil {
		return bloggo.FailMessage(err.Error())
	}
	var data structs.TbCategoryStruct
	data.Id = categoriesDTO.Id
	data.CategoryName = categoriesDTO.CategoryName
	data.UpdateTime = time.Now()
	if data.Id == 0 {
		data.CreateTime = time.Now()
		err = service.SaveTbCategoryStruct(c, &data)
	} else {
		err = service.UpdateNotZeroTbCategoryStruct(c, &data)
	}
	if err != nil {
		return bloggo.FailMessage(err.Error())
	}
	return bloggo.Ok()
}

// DeleteCategories 删除分类
func DeleteCategories(c *gin.Context) *bloggo.R {
	var ids []int
	err := c.ShouldBind(&ids)
	if err != nil {
		return bloggo.FailMessage(err.Error())
	}
	if len(ids) == 0 {
		return bloggo.Ok()
	}
	var count int
	finder := zorm.NewFinder().Append("SELECT COUNT(1) AS count FROM").Append(structs.TbArticleStructTableName)
	finder.Append("WHERE category_id IN (?)", ids)
	_, err = zorm.QueryRow(c, finder, &count)
	if err != nil {
		return bloggo.FailMessage(err.Error())
	}
	if count > 0 {
		return bloggo.FailMessage("删除失败，该分类下存在文章")
	}
	_, err = zorm.Transaction(c, func(ctx context.Context) (interface{}, error) {
		finder = zorm.NewDeleteFinder(structs.TbCategoryStructTableName)
		finder.Append("WHERE id in (?)", ids)
		return zorm.UpdateFinder(ctx, finder)
	})
	if err != nil {
		return bloggo.FailMessage(err.Error())
	}
	return bloggo.Ok()
}
